#include "mycmd.h"
#include "ui_mycmd.h"

MyCMD::MyCMD(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MyCMD)
{
    ui->setupUi(this);
    currentPath = QCoreApplication::applicationDirPath();
    QStringList list = currentPath.split('/');
    currentPath = list[list.length()-1];
    clear(1);
    this->pro = new QProcess;
    pro->setProgram("cmd");
    connect(ui->textEdit_input,SIGNAL(cursorPositionChanged()),this,SLOT(setCursor()));//命令行强制只有最后一行可以编辑
    connect(pro,SIGNAL(readyRead()),this,SLOT(readOutput()));
    connect(ui->action_BlackWrite,SIGNAL(triggered(bool)),this,SLOT(toBlackWrite()));
    connect(ui->action_AppDefault,SIGNAL(triggered(bool)),this,SLOT(toWhiteBlack()));


    //字体部分
    text_type="SimSun";//默认宋体
    set_B=50;//50为正常
    size=11;//默认为11
    set_l = 0;
    setFont();
    toBlackWrite();
}

MyCMD::~MyCMD()
{
    delete ui;
}


void MyCMD::toBlackWrite()
{
    ui->textEdit_input->setTextColor(Qt::white);
    QPalette pal = ui->textEdit_input->palette();
    pal.setBrush(QPalette::Base, Qt::black);
    ui->textEdit_input->setPalette(pal);
    ui->textEdit_input->repaint();

    //需要重新渲染文字
    QString temp = ui->textEdit_input->toPlainText();
    ui->textEdit_input->setText(temp);
}

void MyCMD::toWhiteBlack()
{
    ui->textEdit_input->setTextColor(Qt::black);
    QPalette pal = ui->textEdit_input->palette();
    pal.setBrush(QPalette::Base, Qt::white);
    ui->textEdit_input->setPalette(pal);
    ui->textEdit_input->repaint();

    //需要重新渲染文字
    QString temp = ui->textEdit_input->toPlainText();
    ui->textEdit_input->setText(temp);
}

void MyCMD::setFont()
{
    QFont font(text_type,size,set_B);//字体，大小，是否加粗
    ui->textEdit_input->setFont(font);
}

void MyCMD::on_action_I_triggered()
{
    QFont font;
    if(set_l==0)
    {
        font.setItalic(true);
        set_l=1;
    }
    else
    {
        font.setItalic(false);
        set_l=0;
    }
    ui->textEdit_input->setFont(font);
}

void MyCMD::on_action_B_triggered()
{
    if(set_B==50)
    {
        set_B=75;//75为加粗
    }
    else
    {
        set_B=50;
    }
    this->setFont();
}

void MyCMD::on_action_gitee_triggered()
{
    QDesktopServices::openUrl(QUrl(QLatin1String("https://gitee.com/onlyyyy/MyCMD")));
}

void MyCMD::on_action_sognti_triggered()
{
    text_type="SimSun";
    setFont();
}

void MyCMD::on_action_heiti_triggered()
{
    text_type="Microsoft YaHei";
    setFont();
}

void MyCMD::on_action_xingkai_triggered()
{
    text_type="STXingKai";
    setFont();
}

void MyCMD::on_action_yellowBlack_triggered()
{
    ui->textEdit_input->setTextColor(Qt::yellow);
    QPalette pal = ui->textEdit_input->palette();
    pal.setBrush(QPalette::Base, Qt::black);
    ui->textEdit_input->setPalette(pal);
    ui->textEdit_input->repaint();

    //需要重新渲染文字
    QString temp = ui->textEdit_input->toPlainText();
    ui->textEdit_input->setText(temp);
}

void MyCMD::on_action8_triggered()
{
    size=8;
    setFont();
}


void MyCMD::on_action12_triggered()
{
    size=12;
    setFont();
}

void MyCMD::on_action10_triggered()
{
    size=10;
    setFont();
}

void MyCMD::on_action16_triggered()
{
    size=16;
    setFont();
}

void MyCMD::on_action20_triggered()
{
    size=20;
    setFont();
}

void MyCMD::on_action9_triggered()
{
    size=9;
    setFont();
}

void MyCMD::on_action11_triggered()
{
    size=11;
    setFont();
}

void MyCMD::on_action13_triggered()
{
    size=13;
    setFont();
}

void MyCMD::on_action14_triggered()
{
    size=14;
    setFont();
}

void MyCMD::on_action15_triggered()
{
    size=15;
    setFont();
}

void MyCMD::on_action_green_triggered()
{
    ui->textEdit_input->setTextColor(Qt::green);
    QPalette pal = ui->textEdit_input->palette();
    pal.setBrush(QPalette::Base, Qt::black);
    ui->textEdit_input->setPalette(pal);
    ui->textEdit_input->repaint();

    //需要重新渲染文字
    QString temp = ui->textEdit_input->toPlainText();
    ui->textEdit_input->setText(temp);
}

void MyCMD::on_action_kaiti_triggered()
{
    text_type="KaiTi";
    setFont();
}

void MyCMD::clear(int flag)
{
    ui->textEdit_input->setText(welcome);
    //决定要不要增加一个当前路径
    if(flag == 1)
    {
        ui->textEdit_input->append(currentPath+":");
    }

    //ui->textEdit_input->append("");
    ui->textEdit_input->setFocusPolicy(Qt::StrongFocus);
    ui->textEdit_input->setFocusPolicy(Qt::NoFocus);

    ui->textEdit_input->setFocus();//重设光标
    ui->textEdit_input->installEventFilter(this);//设置完后自动调用其eventFilter函数
    QTextCursor cursor = ui->textEdit_input->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit_input->setTextCursor(cursor);//光标移动到最后一行
    lastCommand = currentPath+":";
}

//响应按键
bool MyCMD::eventFilter(QObject *target, QEvent *event)
{
    if(target == ui->textEdit_input)
    {
        if(event->type() == QEvent::KeyPress)//回车键
        {
             QKeyEvent *k = static_cast<QKeyEvent *>(event);
             if(k->key() == Qt::Key_Return)
             {
                 send();
                 return true;
             }
             if(k->key() == Qt::Key_Backspace)
             {
                 //考虑实现如下功能：判断最后一行的字符长度，过小就不允许删除了
                 if(lastCommand.length() == currentPath.length()+1)
                 {
                     return true;
                 }

             }
        }

    }
    return QWidget::eventFilter(target,event);
}

void MyCMD::send()
{

    QTextCursor cursor = ui->textEdit_input->textCursor();
    cursor.movePosition(QTextCursor::End);

    ui->textEdit_input->setTextCursor(cursor);//光标先移动到最后一行
    QTextDocument *textDocument= ui->textEdit_input->document();
    int lineNumber = cursor.blockNumber();//行号
    QTextBlock textBlock = textDocument->findBlockByLineNumber(lineNumber);
    QString selectLine=textBlock.text();

    lastCommand = selectLine;

    selectLine = selectLine.mid(currentPath.length()+1);
    midedCommand = selectLine;
    std::stringstream input(selectLine.toStdString());//QString转string
    QString result;
    std::string sresult;//对于string与QString的不兼容处理
    while(input>>sresult)
    {
        result=QString::fromStdString(sresult);
        command.push_back(result);//此时vector会依次存放单词

    }
    //开始处理指令
    judge();
    ui->textEdit_input->append(currentPath+":");
    //ui->textEdit_input->append("");

    command.clear();//清空，便于下一条指令获取
    input.clear();
}

void MyCMD::setCursor()//将光标移动到最后一行
{

    QTextCursor cursor = ui->textEdit_input->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit_input->setTextCursor(cursor);//光标移动到最后一行
}

void MyCMD::judge()//处理指令
{
    int length;
    length=command.size();

    if(length == 0)
    {
        return;
    }
    if(command[0]=="ls")
    {
        midedCommand = "dir";
        this->giveWin();            //转交给win10处理
    }
    else if(command[0]=="exit" || command[0] == "quit")
    {
        if(length!=1)
        {
            ui->textEdit_input->append("command exit "+params_error);
            return;
        }
        exit(0);
    }
    else if(command[0]=="clear" || command[0] == "c")
    {
        if(length!=1)
        {
            ui->textEdit_input->append("command clear "+params_error);
        }
        else
        {
            this->clear(0);
        }
    }
    else if(command[0]=="pwd")
    {
        if(length!=1)
        {
            ui->textEdit_input->append("command pwd "+params_error);
        }
        else
        {
            //获取当前程序路径
            QString pwd = QCoreApplication::applicationDirPath();
            ui->textEdit_input->append(pwd);
        }
    }
//    else if(command[0] == "chmod")
//    {
//        this->chmod(length,command);
//    }
    else if(command[0] == "diskinfo")
    {
        this->diskinfo(length);
    }
    else if(command[0] == "md5" || command[0] == "MD5" || command[0] == "Md5")
    {
        this->md5(length,command);
    }
    else if(command[0] == "date")
    {
        this->date(length,command);
    }
    else if(command[0] == "cpu")
    {
        this->cpu(length);
    }
    else if(command[0] == "memory")
    {
        this->memory(length);
    }
    else if(command[0] == "touch")
    {
        this->touch(length,command);
    }
    else if(command[0] == "rm")
    {
        this->rm(length,command);
    }
    else
    {
        this->giveWin();
    }
}

void MyCMD::giveWin()
{
    QStringList argument;
    argument<<"/c"<<midedCommand;
    pro->setArguments(argument);
    pro->start();
    pro->waitForStarted(); //等待程序启动


    //交互式怎么做？
    pro->waitForFinished();//等待程序关闭
    QByteArray by = pro->readAllStandardError();
    //qDebug()<<by;
    lastError = QString::fromLocal8Bit(by);
    QByteArray temp=pro->readAllStandardOutput(); //程序输出信息
    ui->textEdit_input->append(lastError);
}

void MyCMD::readOutput()
{

    out = pro->readAll();

    if(out != "")
    {
        ui->textEdit_input->append(QString::fromLocal8Bit(out));
    }


}

void MyCMD::on_textEdit_input_textChanged()
{
    QTextCursor cursor = ui->textEdit_input->textCursor();
    cursor.movePosition(QTextCursor::End);

    QTextDocument *textDocument= ui->textEdit_input->document();
    int lineNumber = cursor.blockNumber();//行号
    QTextBlock textBlock = textDocument->findBlockByLineNumber(lineNumber);
    QString selectLine=textBlock.text();
    lastCommand = selectLine;
    selectLine = selectLine.mid(currentPath.length()+1);
    midedCommand = selectLine;
}

void MyCMD::chmod(int length,QVector<QString> command)
{
    if(length != 3)
    {
        ui->textEdit_input->append("command chmod "+params_error);
    }
    else
    {
        QString fileName = command[2];
        QString chmods = command[1];
        if(chmods.length()<=1)
        {
            ui->textEdit_input->append("command chmod second "+params_error);
            return;
        }
        QString auth = nullptr;
        //+赋予权限 -免去权限
        if(chmods.mid(0,1)!="+"&&chmods.mid(0,1)!="-")
        {
            ui->textEdit_input->append("command chmod second "+params_error);
            return;
        }
        else if (chmods.mid(0,1) == "+")
        {
            auth = "000";           //rwx
        }
        else
        {
            auth = "111";           //rwx
        }
        if(!QFile::exists(fileName))
        {
            ui->textEdit_input->append("command chmod  "+ file_not_exist);
        }
        else
        {
            QFile file(fileName);

            for(int i=1;i<chmods.length();i++)
            {
                if(chmods[i]== "r")
                {
//                    QFile file(imagePath);
//                    file.setPermissions(QFile::ReadOther | QFile::WriteOther);
                }
                else if(chmods[i] == "w")
                {

                }
                else if(chmods[i] == "x")
                {

                }
                else
                {
                    ui->textEdit_input->append("command chmod  "+ unknown_param);
                }
            }
        }
    }
}

void MyCMD::diskinfo(int length)
{
    if(length!=1)
    {
        ui->textEdit_input->append("command diskinfo "+params_error);
        return;
    }
    QStringList diskList = fs->getDiskName();

        foreach(QString str, diskList)
        {
            if (str.isEmpty())
            {
                continue;
            }
            quint64 totalDiskSpace = fs->getDiskSpace(str, true);
            quint64 freeDiskSpace = fs->getDiskSpace(str, false);
            ui->textEdit_input->append("盘符" + str + "【总容量:"+QString::number(totalDiskSpace) +"GB"\
                     +"\t剩余容量:" + QString::number(freeDiskSpace) + "GB】");

        }
}

//生成md5码
void MyCMD::md5(int length,QVector<QString> command)
{
    if(length != 2)
    {
        ui->textEdit_input->append("command md5 "+params_error);
        return;
    }
    QString dest = command[1];
    QByteArray by = QCryptographicHash::hash(dest.toLatin1(),QCryptographicHash::Md5);
    QString result = by.toHex().toUpper();
//    qDebug()<<result;
    ui->textEdit_input->append(result);
}

//系统时间相关
void MyCMD::date(int length,QVector<QString> command)
{
//    if(length >2)
//    {
//        ui->textEdit_input->append("command date "+params_error);
//        return;
//    }
    QString qStr;
    QDateTime dateTime(QDateTime::currentDateTime());
    if(length == 1)
    {

        qStr = dateTime.toString("yyyy-MM-dd hh:mm:ss ddd");
    }
    else
    {
        QString dateType = nullptr;
        //为了将用户输入的空格识别出来，拼接成日期格式
        for(int i=1;i<command.length();i++)
        {
            if(i == 1)
            {
                dateType += command[i];
            }
            else
            {
                dateType +=" " + command[i];
            }

        }
        qDebug()<<dateType;
        qStr = dateTime.toString(dateType);
    }
    qDebug()<<qStr;
    ui->textEdit_input->append(qStr);
}

//获取cpu利用率
void MyCMD::cpu(int length)
{
    if(length != 1)
    {
        ui->textEdit_input->append("command cpu "+params_error);
        return;
    }
    else
    {
        qDebug()<<fs->getCpuUsage();
        QString result = "CPU use rate:" + QString::number(fs->getCpuUsage())+"%";
        ui->textEdit_input->append(result);
    }
}

//获取内存使用率
void MyCMD::memory(int length)
{
    if(length != 1)
    {
        ui->textEdit_input->append("command momery "+params_error);
        return;
    }
    else
    {
        double nMemTotal = 0,nMemUsed = 0;
        if(!fs->memory(nMemTotal,nMemUsed))
        {
            ui->textEdit_input->append("get memory used failed");
        }
        else
        {
            ui->textEdit_input->append("Memory total: "+ QString::number(nMemTotal) + "MB  Memory used: " +
                                       QString::number(nMemUsed) + "MB");
        }

    }
}



//新建文件
void MyCMD::touch(int length, QVector<QString> command)
{
    if(length != 2)
    {
        ui->textEdit_input->append("command touch "+params_error);
        return;
    }
    QString fileName = command[1];
    QFile file( fileName );
    if ( file.exists())
    {
            ui->textEdit_input->append("file " +fileName + " " + file_already_exists);
    }
    else
    {
        file.open( QIODevice::WriteOnly );
        file.close();
        ui->textEdit_input->append("file "+fileName + " "+created_success);
    }

}

//删除文件
void MyCMD::rm(int length, QVector<QString> command)
{
    if(length != 2)
    {
        ui->textEdit_input->append("command rm "+params_error);
        return;
    }
    QString fileName = command[1];
    QFile file( fileName );
    if ( !file.exists())
    {
            ui->textEdit_input->append("file " +fileName + " " + not_exist);
    }
    else
    {
        file.remove(fileName);
        file.close();
        ui->textEdit_input->append("file "+fileName + " "+deleted_success);
    }
}

void MyCMD::on_action_author_triggered()
{
    QMessageBox::about(nullptr,"作者","吉法师 QQ765715928");
}
